/*
 * file : java/MakeEntry.java
 * google calendar interface. adds a quick entry into google calendar
 * Author : Anil Kainikara (anilkumar911@gmail.com)
 *
 * This code is licenced under the GPL.
 */

import com.google.gdata.client.*;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import com.google.gdata.data.acl.*;
import com.google.gdata.data.calendar.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.net.URL;
import java.util.*;
import java.io.*;


class MakeEntry
{
  public static void main(String args[]){

  Properties props = new Properties();
  String homedir = System.getProperty("user.home");

  try {
    //props.load(new FileInputStream("powerdiary2.properties"));
    props.load(new FileInputStream(homedir + "/.local/share/powerdiary2.properties"));
  } catch( IOException e ){
    e.printStackTrace();
    return;
  }

  String guser = props.getProperty("GCAL_USER");
  String gpass = props.getProperty("GCAL_PASS");


  //System.out.println(" args[0] = " + args[0] + " args[1] = " + args[1] + " args[2] = " + args[2] );

   GoogleService myService = new GoogleService("cl", "powerdiary2");
   //CalendarService myService = new GoogleService("cl", "exampleCo-exampleApp-1");
   URL postUrl=null;
   URL feedUrl=null;
   try{
     myService.setUserCredentials(guser, gpass);
     String urlString="http://www.google.com/calendar/feeds/" + guser + "/private/full";
     postUrl = new URL(urlString);
     feedUrl = new URL("http://www.google.com/calendar/feeds/default/private/full");
   }catch(Exception e){
     e.printStackTrace();
     return;
   }

   //retrive existing entries...
   try {
     Query myQuery = new Query(feedUrl);
     String searchstring = args[0];
     searchstring = searchstring.trim();
     int byindex = searchstring.lastIndexOf("by");
     if(byindex > 0){
       searchstring = searchstring.substring(0,byindex);
     }
     System.out.println("search string is :" + searchstring);
     myQuery.setFullTextQuery(searchstring);
     CalendarEventFeed myResultsFeed = myService.query(myQuery, CalendarEventFeed.class);
     if (myResultsFeed.getEntries().size() > 0){
       System.out.println("entry exists");
       return;
     }
   } catch(Exception e){
     e.printStackTrace();
     return;
   }

    CalendarEventEntry myEntry=new CalendarEventEntry();

    // Send the request and receive the response:
    try{
      //EventEntry insertedEntry = myService.insert(postUrl, myEntry);
      myEntry.setContent(new PlainTextConstruct(args[0]));
      myEntry.setQuickAdd(true);
      myService.insert(postUrl, myEntry);
    }catch(Exception e){
      e.printStackTrace();
      return;
    }
  }
}
